const Koa = require('koa')
const consola = require('consola')
const bodyParser = require('koa-bodyparser')
const { Nuxt, Builder } = require('nuxt')
// Import and Set Nuxt.js options
const config = require('./nuxt.config.js')
const app = new Koa()
config.dev = app.env !== 'production'
const redis = require("./lib/redis") // 你的redis配置文件路径

// Instantiate nuxt.js
const nuxt = new Nuxt(config)
const {
  host = process.env.HOST || '127.0.0.1',
  port = 3001
} = nuxt.options.server

// Build in development
if (config.dev) {
  const builder = new Builder(nuxt)
  builder.build()
} else {
  nuxt.ready()
}
app.use(bodyParser())
// 获取用户session
const auth = require('./middleware/auth.js')
app.use(async (ctx, next) => {
  if(redis){
    ctx.redis = redis;
    // //console.log("获取用户session:middleware auth")
    await auth(ctx);
  }
  await next()
})

// 注册API路由
const router = require('./api/index.js')
app.use(router.routes(), router.allowedMethods())





app.use((ctx) => {
  ctx.status = 200
  // ctx.session.username="winn2";
  // return
  ctx.respond = false // Bypass Koa's built-in response handling
  nuxt.render(ctx.req, ctx.res)
})

app.listen(port, host)
consola.ready({
  message: `Server listening on http://${host}:${port}`,
  badge: true
})
